package fr.hoteia.appengine.archetype.server.web.util;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

import com.google.gdata.util.common.base.StringUtil;
import com.google.gdata.util.common.util.Base64;
import com.google.gdata.util.common.util.Base64DecoderException;

/**
 * <p>
 * <a href="RsaKeyUtil.java.html"><i>View Source</i></a>
 * </p>
 *
 * RsaKeyUtil is use to inject your RsaKey which is necessary for OAuth Google.
 * 
 * @author Denis GOSSET <a href="http://www.hoteia.com"><i>Hoteia.com</i></a>
 * 
 */
public class RsaKeyUtil {

	public static PrivateKey getPrivateKey() {

		try {
			KeyFactory fac = KeyFactory.getInstance("RSA");

			EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decode(getPrivateKeyAsByte()));

			return fac.generatePrivate(privKeySpec);

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (Base64DecoderException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] getPrivateKeyAsByte() {

		StringBuffer strBuffer = new StringBuffer();

		strBuffer.append("YOURKEY");

		byte[] privKeyBytes = StringUtil.latin1ToBytes(strBuffer.toString());

		return privKeyBytes;
	}
}
